package zsy.springframework.beans.factory.chouxiang;

import zsy.springframework.beans.factory.BeansException;
import zsy.springframework.beans.factory.config.BeanDefinition;
import zsy.springframework.beans.factory.jiekou.BeanFactory;
import zsy.springframework.beans.factory.support.DefaultSingletonBeanRegistry;

//既实现了getbean这个接口，有继承了这个单例获取对象的方法
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {


    @Override
    public Object getBean(String beanName, Object... args) throws BeansException {
        return doGetBean(beanName, args);
    }


    @Override
    public Object getBean(String beanName) throws BeansException {
//        Object singleton = getSingleton(beanName);
//        if (singleton != null) {
//            return singleton;
//        }
//        BeanDefinition beanDefiniton = getBeanDefiniton(beanName);
//
//        return createBean(beanName, beanDefiniton);
        //将上面这个方法抽取出来
        return doGetBean(beanName, null);
    }

    protected <T> T doGetBean(String beanName, final Object[] args) {
        Object bean = getSingleton(beanName);
        if (bean != null) {
            return (T) bean;
        }
        BeanDefinition beanDefiniton = getBeanDefiniton(beanName);
        return (T) createBean(beanName, beanDefiniton, args);
    }

    protected abstract Object createBean(String beanName, BeanDefinition beanDefiniton, Object[] args) throws BeansException;

    protected abstract BeanDefinition getBeanDefiniton(String beanName) throws BeansException;
}
